<template>
    <div style="height: 100%">
        <el-tabs style="height: 100%" type="card" v-if="type != '6'">
            <el-tab-pane>
                <span slot="label"> {{ computedLabel }}</span>
                <div class="position-box" v-if="['1', '4', '5', '10', '11', '12', '13'].includes(type)">
                    <risk-table
                        v-loading="stockLoading"
                        :key="positionTableKey"
                        :msg="fundPositionsListMsg"
                        @getList="queryFundPositionList"
                        @handleFilter="handleFilterFundPosition"
                    ></risk-table>
                </div>

                <div class="position-box" v-else-if="type == '2'">
                    <risk-table
                        v-loading="stockLoading"
                        key="bid"
                        :msg="bidStockListMsg"
                        @getList="queryBidStockList"
                        @handleFilter="handleFilterFundPosition"
                        @handleBtn="handleSelect"
                    ></risk-table>
                </div>

                <div class="position-box" v-else-if="type == '3'">
                    <risk-table
                        key="purchase"
                        v-loading="stockLoading"
                        :msg="purchaseStockListMsg"
                        @getList="queryPurchaseStockList"
                        @handleFilter="handleFilterFundPosition"
                        @handleBtn="handleSelect"
                    ></risk-table>
                </div>

                <!-- 存单信息 -->
                <div class="position-box" v-else-if="['7', '8'].includes(type)">
                    <risk-table
                        key="deposit"
                        class="summary-table"
                        v-loading="stockLoading"
                        :msg="depositReceiptListMsg"
                        @getList="queryDepositPositionList"
                        @handleFilter="handleFilterFundPosition"
                    ></risk-table>
                </div>

                <div class="position-box" v-else-if="type == '9'">
                    <risk-table
                        key="paid"
                        v-loading="stockLoading"
                        :msg="withdrawListMsg"
                        @getList="queryWithdrawDepositList"
                        @handleFilter="handleFilterFundPosition"
                        @handleBtn="handleSelect"
                    ></risk-table>
                </div>
            </el-tab-pane>
        </el-tabs>
        <el-tabs style="height: 100%" type="card" v-else>
            <el-tab-pane label="可质押债券">
                <div class="position-box">
                    <risk-table
                        :key="pledgeTableKey"
                        class="summary-table"
                        v-loading="stockLoading"
                        :msg="pledgePositionsListMsg"
                        @getList="queryPledgeList"
                        @handleFilter="handleFilterPledgePosition"
                        @handleBtn="handleSelect"
                    ></risk-table>
                </div>
            </el-tab-pane>
            <el-tab-pane label="产品持仓信息">
                <div class="position-box">
                    <risk-table
                        v-loading="stockLoading"
                        :key="positionTableKey"
                        :msg="baybackPositionsListMsg"
                        @getList="getBuyBackPosiotion"
                        @handleFilter="handleFilterFundPosition"
                    ></risk-table>
                </div>
            </el-tab-pane>
        </el-tabs>
    </div>
</template>
<script lang="ts">
import RiskTable from '@/common/components/risk-table.vue';
import DictionConstUtil, { SGU_CACHE } from '@/utils/diction-const-util';
import { numberFormat } from '@/utils/tools';
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import { getFundPosition } from '../../api';
import ColumnUtil from '../../utils/column-util';

@Component({
    name: 'PositionInfo',
    components: {
        RiskTable,
    },
})
// 各指令持仓信息
export default class PositionInfo extends Vue {
    @Prop()
    type: string;
    @Prop()
    fundCode: string;
    @Prop()
    fundAccountCode: string;
    @Prop()
    selectPosition: string;
    @Prop({
        default: () => {
            return {};
        },
    })
    assetInfo: any;
    ColumnUtil = new ColumnUtil();
    allStockType: any[] = []; // 所有证券类别数据
    // 分页
    pages = { currentPage: 1, pageSize: 25 };

    // 产品持仓信息相关
    fundPositionsListMsg: any = {
        returnData: { data: [], total: 0 },
        dataKey: 'data',
        title: this.ColumnUtil.proPositionColumns,
        height: '100%',
        // 隐藏页码
        hidePage: false,
        checked: { on: false, option: false },
    };

    // 回购持仓
    baybackPositionsListMsg: any = {
        returnData: { data: [], total: 0 },
        dataKey: 'data',
        title: this.ColumnUtil.repoPositionColums,
        showFooter: true,
        footerMethod: this.getSummaries,
        height: '100%',
        // 隐藏页码
        hidePage: false,
        checked: { on: false, option: false },
    };

    // 可投标债券信息
    bidStockListMsg = {
        returnData: { data: [], total: 0 },
        dataKey: 'data',
        title: this.ColumnUtil.bidStockColumns,
        height: '100%',
        // 隐藏页码
        hidePage: false,
        checked: { on: false, option: false },
    };

    // 可申购证券信息相关
    purchaseStockListMsg = {
        returnData: { data: [], total: 0 },
        dataKey: 'data',
        title: this.ColumnUtil.UnderNetStockColumns,
        height: '100%',
        // 隐藏页码
        hidePage: false,
        checked: { on: false, option: false },
    };
    selectedStock: any = {}; // 勾选的证券

    // 存款持仓
    depositReceiptListMsg: any = {
        returnData: { data: [], total: 0 },
        dataKey: 'data',
        title: this.ColumnUtil.CKPositionsColumns,
        height: '100%',
        // 隐藏页码
        hidePage: false,
        showFooter: true,
        footerMethod: this.getDepositSummaries,
        checked: { on: false, option: false },
    };

    // 可支取存单信息
    withdrawListMsg: any = {
        returnData: { data: [], total: 0 },
        dataKey: 'data',
        title: this.ColumnUtil.CKPositionsColumns,
        height: '100%',
        // 隐藏页码
        hidePage: false,
        checked: { on: false, option: false },
    };

    // 可选质押券信息相关
    pledgePositionsListMsg = {
        returnData: { data: [], total: 0 },
        dataKey: 'data',
        title: this.ColumnUtil.pledgeColumns,
        height: '100%',
        // 隐藏页码
        hidePage: false,
        checked: { on: false, option: false },
    };

    fundFilterList: any[] = [];
    stockCodeKey: string = '';
    stockNameKey: string = '';

    pledgeFilterList: any[] = [];
    stockCode2: string = '';
    stockName2: string = '';

    positionTableKey: number = 0;
    pledgeTableKey: number = 0;

    stockInfo: any = {};
    instructionCache: any = {};

    showType: string = '1'; // 回购持仓显示
    stockTypePojo: any = {};

    // 指令类型(前端定义,不对应后端)与业务类型对应关系
    instToBusinessTypePojo: any = {
        '1': '1',
        '4': '1',
        '5': '2',

        '10': 'E',
        '11': 'I',
        '12': '4',
        '13': 'A',
    };
    businessType: string = '';
    stockLoading: boolean = false;
    repoSummary: any = {}; // 回购持仓汇总对象
    depositSummary: any = {}; // 存款持仓汇总对象
    label: string = '产品持仓信息'; // 标签页标题

    async mounted() {
        // 获取所有证券类别 (用于筛选订单方向)
        this.allStockType = await SGU_CACHE('StockType', '/dict/stockType/list', []);
        this.stockTypePojo = DictionConstUtil.ListToPojo(await SGU_CACHE('StockType', '/dict/stockType/list', []));
    }

    get computedLabel() {
        let label: string = '';
        if (this.type == '2') {
            label = '可投标债券信息';
        } else if (this.type == '3') {
            label = '可申购证券信息';
        } else if (this.type == '9') {
            label = '可支取存单';
        } else {
            label = '产品持仓信息';
        }
        return label;
    }

    @Watch('type', { immediate: true, deep: true })
    onWatchType() {
        if (this.type === '12') {
            this.fundPositionsListMsg.title = this.ColumnUtil.FuturesPositionColumns;
        } else if (['1', '4', '5', '10', '11', '13'].includes(this.type)) {
            this.fundPositionsListMsg.title = this.ColumnUtil.proPositionColumns;
            console.log(this.fundPositionsListMsg.title, 'fundPositionsListMsg.title');
        } else if (this.type == '9') {
            let title: any[] = [];
            title = JSON.parse(JSON.stringify(this.ColumnUtil.CKPositionsColumns));
            title.unshift({
                name: '操作',
                type: 'btn',
                width: 60,
                fixed: 'left',
                btns: [
                    {
                        type: 'primary',
                        icon: 'el-icon-check',
                        isDisabled: value => value['disabled'],
                    },
                ],
            });
            this.withdrawListMsg.title = JSON.parse(JSON.stringify(title));
        }
        this.positionTableKey++;
        this.fundFilterList = [];
        this.businessType = this.instToBusinessTypePojo[this.type];
        this.queryPositions(this.type);
    }

    // 监听产品代码变化，获取产品持仓
    @Watch('fundCode', { immediate: true, deep: true })
    onWatchFundCode(newValue, oldValue) {
        this.fundFilterList = [];
        this.positionTableKey++;
        if (JSON.stringify(newValue) != JSON.stringify(oldValue) && this.fundCode) {
            // 可投标债券和可申购债券不受产品影响
            if (!['2', '3'].includes(this.type)) {
                this.queryPositions(this.type);
            }
        }
        if (!this.fundCode) {
            this.fundPositionsListMsg.returnData.data = [];
            this.fundPositionsListMsg.returnData.total = 0;
        }
    }

    // 监听组合编码变化，获取产品持仓
    @Watch('fundAccountCode', { immediate: true, deep: true })
    onWatchFundAccountCode(newValue, oldValue) {
        this.fundFilterList = [];
        this.positionTableKey++;
        if (JSON.stringify(newValue) != JSON.stringify(oldValue)) {
            if (!['2', '3'].includes(this.type)) {
                this.queryPositions(this.type);
            }
        }
    }

    @Watch('selectPosition', { immediate: true, deep: true })
    onWatchSelect(newValue, oldValue) {
        if (JSON.stringify(newValue) !== JSON.stringify(oldValue)) {
            this.handleSelect({});
        }
    }

    hanldeChangeShow(type: string) {
        this.showType = type;
    }

    queryPositions(showFormType: string) {
        switch (showFormType) {
            case '2':
                // 查询可投标债券
                this.queryBidStockList(this.pages);
                break;
            case '3':
                // 查询可申购债券
                this.queryPurchaseStockList(this.pages);
                break;
            case '6':
                // 查询可质押债券
                this.queryPledgeList(this.pages);
                // 查询产品持仓
                if (this.fundCode) {
                    this.getBuyBackPosiotion(this.pages);
                }
                break;
            case '7':
            case '8':
                // 查询在途存单
                this.queryDepositPositionList(this.pages);
                break;
            case '9':
                // 查询可支取存单
                // if (this.fundCode) {
                this.queryWithdrawDepositList(this.pages);
                // }
                break;
            default:
                // 查询产品持仓
                this.queryFundPositionList(this.pages);
                break;
        }
    }

    // 查询可投标债券信息
    queryBidStockList(pages: any) {
        this.stockLoading = true;
        let form: any = {};
        // 判断是否带过滤条件
        if (!this.fundFilterList.length) {
            form = {
                isBid: 1,
                paging: pages,
            };
        } else {
            form = {
                isBid: 1,
                stockCode: this.stockCodeKey,
                stockName: this.stockNameKey,
                paging: pages,
            };
        }
        // 获取产品持仓信息
        this.$axios
            .post('/primaryBond/list', form)
            .then((res: any) => {
                this.bidStockListMsg.returnData.data = res.list;
                this.bidStockListMsg.returnData.total = res.total;
                if (JSON.stringify(this.selectedStock) == '{}') {
                    this.handleStockStatus(this.bidStockListMsg.returnData.data, this.stockInfo, 'bondCode');
                } else {
                    this.handleStockStatus(this.bidStockListMsg.returnData.data, this.selectedStock, 'bondCode');
                }
                this.stockLoading = false;
            })
            .catch(() => {
                this.stockLoading = false;
            });
    }

    // 查询可申购债券信息
    queryPurchaseStockList(pages: any) {
        this.stockLoading = true;
        let form: any = {};
        // 判断是否带过滤条件
        if (!this.fundFilterList.length) {
            form = {
                paging: pages,
            };
        } else {
            form = {
                stockCode: this.stockCodeKey,
                stockName: this.stockNameKey,
                paging: pages,
            };
        }
        // 获取产品持仓信息
        this.$axios
            .post('/position/stock/offlineSubs', form)
            .then((res: any) => {
                this.handleStockStatus(res.list, this.selectPosition, 'stockCode');
                this.purchaseStockListMsg.returnData.data = res.list;
                this.purchaseStockListMsg.returnData.total = res.total;
                this.stockLoading = false;
            })
            .catch(() => {
                this.stockLoading = false;
            });
    }

    // 查询存款持仓
    queryDepositPositionList(pages: any) {
        let form: any = {};
        form = {
            fundCode: [this.fundCode],
            paging: this.pages,
        };
        // 获取产品持仓信息
        this.$axios.post('/position/bankDeposit/fund', form).then((res: any) => {
            if (res.summary) {
                this.depositSummary = res.summary;
            }
            res.list.forEach(ele => {
                ele.totalBalance = Number(ele.balance || '0') + Number(ele.receivableInterest || '0');
                ele.assetCode = ele.assetCode || this.assetInfo.assetCode;
                ele.assetName = ele.assetName || this.assetInfo.assetName;
            });
            this.depositReceiptListMsg.returnData.data = res.list;
            this.depositReceiptListMsg.returnData.total = res.total;
        });
    }

    // 可支取存单信息
    queryWithdrawDepositList(pages: any) {
        let form: any = {};
        form = {
            fundCode: [this.fundCode],
            paging: pages,
        };
        // 获取可支取存单信息
        this.$axios.post('/position/bankDeposit/receipt/fund', form).then((res: any) => {
            res.list.forEach(ele => {
                ele.totalBalance = Number(ele.balance || '0') + Number(ele.receivableInterest || '0');
            });
            this.withdrawListMsg.returnData.data = res.list;
            this.withdrawListMsg.returnData.total = res.total;
        });
    }

    // 产品持仓信息
    queryFundPositionList(pages: any) {
        this.stockLoading = true;
        let form: any = {};
        // 判断是否带过滤条件
        if (!this.fundFilterList.length) {
            form = {
                businessType: this.businessType,
                fundCode: [this.fundCode],
                fundAcCode: [this.fundAccountCode],
                paging: pages,
            };
        } else {
            form = {
                businessType: this.businessType,
                stockCode: this.stockCodeKey,
                stockNameSt: this.stockNameKey,
                fundCode: [this.fundCode],
                fundAcCode: [this.fundAccountCode],
                paging: pages,
            };
        }
        if (this.type == '4') {
            form.refinancing = true;
        }
        // 获取产品持仓信息
        getFundPosition(form)
            .then((res: any) => {
                this.fundPositionsListMsg.returnData.data = res.list;
                this.fundPositionsListMsg.returnData.total = res.total;

                this.fundPositionsListMsg.returnData.data.forEach(ele => {
                    ele.assetCode = ele.assetCode || this.assetInfo.assetCode;
                    ele.assetName = ele.assetName || this.assetInfo.assetName;
                    for (let i = 0; i < this.allStockType.length; i++) {
                        const item = this.allStockType[i];
                        if (ele.stockType == item.dictKey) {
                            ele.stockType = item.dictKeyName;
                        }
                    }
                });
                this.stockLoading = false;
            })
            .catch(err => {
                this.yh_message_error(err);
                this.stockLoading = false;
            });
    }

    // 银行间回购产品持仓
    getBuyBackPosiotion(pages: any) {
        let form: any = {};
        // 判断是否带过滤条件
        if (!this.fundFilterList.length) {
            form = {
                fundCode: [this.fundCode],
                paging: pages,
            };
        } else {
            form = {
                stockCode: this.stockCodeKey,
                stockName: this.stockNameKey,
                fundCode: [this.fundCode],
                paging: pages,
            };
        }
        // 银行间回购指令产品实时持仓
        this.$axios.post('/position/bankRepo/fund', form).then((res: any) => {
            if (res.summary) {
                this.repoSummary = res.summary;
            }

            res.list.forEach(ele => {
                ele.stockType = this.stockTypePojo[ele.stockType];
                ele.assetCode = ele.assetCode || this.assetInfo.assetCode;
                ele.assetName = ele.assetName || this.assetInfo.assetName;
            });
            this.baybackPositionsListMsg.returnData.data = res.list;
            this.baybackPositionsListMsg.returnData.total = res.total;
        });
    }

    // 回购持仓合计行
    getSummaries() {
        let arr = [];
        if (this.baybackPositionsListMsg.returnData.data.length) {
            let count = 0;
            let objR = this.repoSummary;
            for (let item of this.baybackPositionsListMsg.title) {
                if (item.val == 'ghBalance') {
                    arr[count++] = numberFormat(objR[item.val], 2) || '--';
                } else {
                    arr[count++] = objR[item.val] || '--';
                }
            }
        }
        return [arr];
    }

    // 存款持仓合计行
    getDepositSummaries() {
        let arr = [];
        if (this.depositReceiptListMsg.returnData.data.length) {
            let count = 0;
            let objR = this.depositSummary;
            objR.receivableInterest = this.depositSummary.interest;
            objR.totalBalance = this.depositSummary.interest + this.depositSummary.balance;
            for (let item of this.depositReceiptListMsg.title) {
                if (['balance', 'interest', 'punishInterest', 'totalBalance'].includes(item.val)) {
                    arr[count++] = numberFormat(objR[item.val], 2) || '--';
                } else {
                    arr[count++] = objR[item.val] || '--';
                }
            }
        }
        return [arr];
    }

    // 查询可质押债券
    queryPledgeList(pages) {
        let form: any = {};
        // 判断是否带过滤条件
        if (!this.pledgeFilterList.length) {
            form = {
                fundCode: [this.fundCode],
                paging: pages,
            };
        } else {
            form = {
                stockCode: this.stockCode2,
                stockNameSt: this.stockName2,
                fundCode: [this.fundCode],
                paging: pages,
            };
        }
        // 获取可质押债券
        this.$axios.post('position/stock/pledge', form).then((res: any) => {
            this.pledgePositionsListMsg.returnData.data = res.list.map(ele => {
                ele.assetCode = ele.assetCode || this.assetInfo.assetCode;
                ele.assetName = ele.assetName || this.assetInfo.assetName;
                return ele;
            });
            this.pledgePositionsListMsg.returnData.total = res.total;
            this.handleStockStatus(this.pledgePositionsListMsg.returnData.data, this.selectPosition, 'stockCode');
        });
    }

    handleSelect(obj: any) {
        // this.stockInfo = obj.row;
        this.selectedStock = obj.row;
        // this.selectedStock.disabled = !this.selectedStock.disabled;
        switch (this.type) {
            case '2':
                this.handleStockStatus(this.bidStockListMsg.returnData.data, this.selectPosition, 'stockCode');
                break;
            case '3':
                this.handleStockStatus(this.purchaseStockListMsg.returnData.data, this.selectPosition, 'stockCode');
                break;
            case '6':
                if (obj && obj?.row) {
                    let obj1 = {
                        totalFacePrice: obj.row.totalPrice,
                        pledgeRatio: '100',
                        pledgedQty: obj.row['currentAmount'],
                        balance: '',
                    };
                    obj1.balance = String((Number(obj1.totalFacePrice || '0') * Number(obj1.pledgeRatio || '0')) / 100);
                    this.selectedStock = { ...obj.row, ...obj1 };
                }
                this.handleStockStatus(this.pledgePositionsListMsg.returnData.data, this.selectPosition, 'stockCode');
                break;
            default:
                break;
        }
        if (this.selectedStock) {
            this.$emit('getSelectPosition', this.selectedStock);
        }
    }

    /**
     * 设置券选中状态
     * @param stockCodeData 当前所有券数据
     * @param selectStockCode 选中券
     * @param key 判断字段
     */

    handleStockStatus(stockCodeData: any, selectStockCode: any, key: string): void {
        console.log('handleStockStatus');
        if (!selectStockCode) {
            return;
        }
        if (this.type === '2') {
            stockCodeData.forEach(ele => {
                let obj = selectStockCode.find(i => i['stockCode'] === ele['bondCode']);
                if (obj) {
                    this.$set(ele, 'disabled', true);
                } else {
                    this.$set(ele, 'disabled', false);
                }
            });
        } else {
            setTimeout(() => {
                stockCodeData.forEach(ele => {
                    let obj = selectStockCode.find(i => i[key] === ele[key]);
                    if (obj) {
                        this.$set(ele, 'disabled', true);
                    } else {
                        this.$set(ele, 'disabled', false);
                    }
                });
            }, 100);
        }
    }

    // 表头筛选
    handleFilterFundPosition(filterList: any) {
        this.fundFilterList = filterList;
        this.stockCodeKey = '';
        this.stockNameKey = '';
        if (filterList.length) {
            let code = filterList.find(ele => ele.property === 'stockCode');
            let name = filterList.find(ele => ['stockNameSt', 'stockName'].includes(ele.property));
            this.stockCodeKey = code?.datas[0] || '';
            this.stockNameKey = name?.datas[0] || '';
        }
        this.queryPositions(this.type);
    }

    // 表头筛选
    handleFilterPledgePosition(filterList: any) {
        this.pledgeFilterList = filterList;
        this.stockCodeKey = '';
        this.stockNameKey = '';
        if (filterList.length) {
            let code = filterList.find(ele => ele.property === 'stockCode');
            let name = filterList.find(ele => ele.property === 'stockNameSt');
            this.stockCode2 = code?.datas[0] || '';
            this.stockName2 = name?.datas[0] || '';
        }
        this.queryPositions(this.type);
    }
}
</script>
<style lang="scss" scoped>
.position-box {
    height: 100%;
    // .title-label {
    //     color: #1890ff;
    //     margin-right: 5px;
    //     text-decoration: underline;
    // }
    // /deep/.vxe-table .vxe-table--body-wrapper.body--wrapper {
    //     min-height: 70px;
    // }
}
</style>
